/* *
* 金额格式化
* */

function f(s, type) {
    if(s === "" || s == null){
        return '';
    }

    if(isNaN(s)){
        return '';
    }

    let newS = parseFloat(s)

    if (type === '万') {
        newS = newS/10000
    }
    let i = newS >= 0 ? '' : '-'
    let val = Math.abs(newS.toFixed(2)).toString()
    let intVal = val.split('.')[0]
    let floatVal = val.split('.')[1]
    if (intVal.length > 3) {
        let reg = /\d{1,3}(?=(\d{3})+$)/g
        intVal = intVal.replace(reg, '$&,')
    }
    if (!floatVal) {
        floatVal = '00'
    } else if (floatVal.length < 2) {
        floatVal += '0'
    }
    return `${i}${intVal}.${floatVal}${type ? type : ''}`
}

export default {
    install(Vue){

        Object.defineProperty(Vue.prototype.$bui, 'formatAmount', {
            value:f
        })

        //金额过十万的,以小数方式呈现 
        Vue.filter('amount', (val,unit='') => {
            if (val==null || isNaN(val)) return;

            
            let n = Number(val)
            let minus = ''

            // 统一按正数计算
            if (n<0) {
                n = Math.abs(n)
                minus = '-' //负数记录符号,在最终字符串上加上
            }

            let formatStr = '' //处理阶段的字符串

            if (n>=10000 && unit==='万') {//绝对值大于十万增加文字单位
                formatStr= f(n/10000) + '万'
            }else{
                formatStr = f(n)
            }

            return minus + formatStr
        })

    }
}
